<!-- 创建任务 -->
<template>
  <!--size="600px"-->
  <el-drawer
    :size="drawWidth"
    title="创建任务"
    :visible="visible"
    @close="updateVisible(false)">
    <div v-show="stepsActive==0">
      <el-form
        :rules="rules"
        label-position="left"
        label-width="110px"
        class="btn-padding"
        :show-message="false"
        :hide-required-asterisk="false"
        ref="form"
        :model="form"
        @keyup.enter.native="submit"
        @submit.native.prevent
      >
        <div class="padding20">
          <el-form-item label="任务名称" class="set-class check-star"  prop="taskName">
            <el-input class="m-top10" v-model="form.taskName" placeholder="请输入任务名称"/>
          </el-form-item>
          <el-form-item label="已选形象" class="set-class check-star"
                        prop="imageId"
                        :rules="!form.imageId  ? { required: true, message: '请选择形象', trigger: ['blur','change']} : {required: false}">
            <div style="margin: 44px 10px 0;">
              <img :src="detailInfo.image" style="height: 150px" v-if="detailInfo.image" />
              <div v-else class="img-btn flex" @click="openImage">+</div>
            </div>
          </el-form-item>
          <el-form-item label="背景图上传" class="flex-columns check-star set-class"
                        prop="backgroundImage"
                        :rules="!form.backgroundImage  ? { required: true, message: '请上传背景图', trigger: ['blur','change']} : {required: false}"
                        v-if="detailInfo.image"
          >
            <div class="flex-between upload-class">
              <!--resolutionType 分辨率类型 3.竖屏  4.横屏 -->
              <div class="font-overflow">建议上传{{detailInfo.resolutionType==4 ? '1920px * 1080px' :'1080px * 1920px'}}尺寸</div>
            </div>
            <ele-image-upload
              :item-style="{width: detailInfo.resolutionType==4 ?'192px' :'108px', height: detailInfo.resolutionType==4 ?'108px' :'192px'}"
              :before-upload="beforeAvatarUpload"
              accept=".jpg,.jpeg,.png"
              :limit="1"
              :multiple="false"
              v-model="bgImgs"
              :auto-upload="false"
              :before-remove="onBeforeRemove"
            />
          </el-form-item>
          <el-form-item label="字幕类型" prop="name"  class="check-star">
            <el-radio-group v-model="form.titleType" @input="explainSet">
              <el-radio :label="1">语音文件</el-radio>
              <el-radio :label="2">添加字幕</el-radio>
            </el-radio-group>
          </el-form-item>

          <!--全程解说——音频-->
          <div v-if="form.titleType==1" class="no-check-star">
            <el-form-item label="全程解说" prop="voiceFiles"
                          :rules="!form.voiceFiles  ? { required: true, message: '请上传全程解说', trigger: ['blur','change']} : {required: false}">
              <el-upload
                :auto-upload="false"
                class="el-upload-class"
                :show-file-list="false"
                :action="ossUrl"
                accept=".mp3,.m4a,.aac"
                :multiple="false"
                :on-change="uploadClick"
                :file-list="fileList">
                <el-button class="width100">+点击上传语音文件</el-button>
              </el-upload>
            </el-form-item>
            <!--可多个上传 -->
            <el-form-item label="全程解说" v-if="explanList.length>0"
            >
              <div class="d-musiz-class">
                <div class="flex-between m-bottom10" v-for="(i,j) in explanList" :key="j">
                  <div class="flex-align-center">
                    <img src="@/assets/music.png" />
                    {{i.bgmName ? i.bgmName : i.fileName}}
                  </div>
                  <el-button @click="clearExplan(j)" icon="el-icon-close"></el-button>
                </div>
              </div>
            </el-form-item>
          </div>
          <!--字幕-->
          <div v-if="form.titleType==2">
            <!-- <el-scrollbar
               style="height: 456px"
               wrapStyle="overflow-x: hidden;"
               viewStyle="padding: 14px 10px;"
             >-->
            <!--是否展示字幕：开关 ，默认开启-->
            <el-form-item label="是否展示字幕" class="check-star">
              <el-switch
                :active-value="1"
                :inactive-value="2"
                v-model="form.showSubtitles">
              </el-switch>
            </el-form-item>
            <el-form-item label="选择人声" class="check-star" v-if="form.imageId"
                          prop="voice"
                          :rules="!form.voice  ? { required: true, message: '请选择人声', trigger: ['blur','change']} : {required: false}">
              <!--voice-->
              <el-select
                v-model="form.voice"
                placeholder="请选择人声"
                class="ele-block"
                clearable
              >
                <el-option :label="i.szr_name" :value="i.voice" v-for="(i,j) in aiList" :key="j" />
              </el-select>
            </el-form-item>
            <el-form-item label="音量" class="form-item-padding check-star">
              <el-slider
                class="slider-class"
                :max="100"
                :min="0"
                input-size="mini"
                v-model="form.volume"
                show-input>
              </el-slider>
            </el-form-item>
            <!--负数为快，0为正常，正数为慢-->
            <el-form-item label="语速" class="form-item-padding check-star">
              <el-radio-group v-model="form.speechSpeed" size="small">
                <!--<el-radio-button label="-500">慢速</el-radio-button>-->
                <el-radio-button label="0">正常</el-radio-button>
                <el-radio-button label="250">较快</el-radio-button>
                <el-radio-button label="500">快速</el-radio-button>
              </el-radio-group>
              <!--<el-slider
                class="slider-class"
                :max="500"
                :min="-500"
                input-size="mini"
                v-model="form.speechSpeed"
                show-input>
              </el-slider>-->
            </el-form-item>
            <!--<el-form-item label="语调" class="form-item-padding check-star">
              <el-slider
                class="slider-class"
                :max="500"
                :min="-500"
                input-size="mini"
                v-model="form.intonation"
                show-input>
              </el-slider>
            </el-form-item>-->
            <div v-for="(item, index) in form.textList" :key="index">
              <!--校检表单-->
              <!-- <el-form-item :label="'字幕'+(index+1)" :prop="'textList.'+index+'.content'" :rules="rules.contents" class="form-item-padding">-->
              <el-form-item :label="'字幕'+(index+1)" :prop="'textList.'+index+'.isText'" :rules="!form.textList[index].isText  ? { required: true, message: '请输入字幕，最低5个字符', trigger: ['blur','change']} : {required: false}" class="form-item-padding">
                <div style="display:flex;">
                  <el-input
                    type="textarea"
                    :rows="2" v-model="item.content" placeholder="请输入字幕文本" class="e-input" @input="changeMney(item,index)" />
                  <!--                <el-button class="btn-position" @click="add" v-if="form.textList.length-1==index" >+{{index}}</el-button>-->
                  <el-button class="btn-position" @click="add" v-if="0==index" >+</el-button>
                  <el-button class="btn-position" @click="subtract(index)" v-else >-</el-button></div>
              </el-form-item>
            </div>
            <!--</el-scrollbar>-->
          </div>
        </div>
      </el-form>
      <!--<div class="flex-end btn-absolute">
        <el-button round @click="resetting">重置</el-button>
        <el-button type="primary" class="margin20" round  @click="confirm()" :loading="loading">提交</el-button>
      </div>-->
      <div class="flex-end btn-absolute">
        <el-button round type="primary" class="margin20" :loading="loading" @click="stepsNext">下一步</el-button>
      </div>
    </div>
    <!--预计点数展示-->
    <div v-show="stepsActive==1">
      <div class="d-point-cls flex-align-center">预计消费点数:<span>{{point || '0'}}</span></div>
      <div class="flex-end btn-absolute">
        <el-button round @click="stepsPrev">上一步</el-button>
        <!--<el-button round @click="resetting">重置</el-button>-->
        <el-button type="primary" class="margin20" round  @click="confirm()" :loading="loading">提交</el-button>
      </div>
    </div>
    <!--打开形象-->
    <open-image ref="image" @getImage="show"></open-image>
  </el-drawer>
</template>

<script>
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  import {ossUpdate2, registerAssetsMedia, userOssSignature} from "@/api/creatCenter/material";
  import {createTask, getAiList,getSubmitAudioProduceJob } from "@/api/digitalHumanManagement/imageDisplay";
  import {getToken} from "@/utils/token-util";
  import axios from "axios";
  import OpenImage from "@/views/digitalHumanManagement/imageDisplay/components/open-image";
  export default {
    name: "create-task",
    components: {OpenImage, EleImageUpload},
    props:{
      visible:Boolean
    },
    data(){
      const defaultForm = {
        showSubtitles:1,  // 是否显示字幕：1_是 2_否
        volume:50,  // 音量
        speechSpeed:0,  // 语速
        intonation:0,  // 语调

        voiceFiles:[],
        backgroundImage:'',  // 背景图
        // 解说音频设置需要
        titleType:1, // 修改，需改为1
        // 口播音频需要（摄像头文本）
        textList:[{
          content:'',
          isText:'' //from 只能判断空值
        }],
        texts:'',
        merchantId: this.$store.state.user.info.merchantId  // 商家id
      }
      return{
        // 预计消费点数
        point:0,
        drawWidth:'60%',
        // 步骤条 进度
        stepsActive: 0,
        // isNewImage为true，代表是新表格创建任务，那么提交或者关闭时，需要清除形象内容
        isNewImage:false,
        // 发布详情
        detailInfo:{},
        bgImgs:[],
        loading:false,
        explanList:[],
        // 上传背景图片url
        fileList:[],
        defaultForm,
        form:{ ...defaultForm },
        // form:JSON.parse(JSON.stringify(defaultForm)),
        rules: {
          taskName: [
            {
              required: true,
              message: '请输入任务名称',
              trigger: 'blur'
            }
          ],

          /*contents: [
            { required: true,
              message: '请添加字幕',
              trigger: 'blur',
            },
            {
              pattern: /^.{5,}$/,
              message: '请最低输入5个字符',
              trigger: 'blur'
            }
          ],*/
        },
        // 数字人AI人声list
        aiList:[]
      }
    },
    methods:{
      /* 上一步 */
      stepsPrev() {
        this.stepsActive--;
        this.drawWidth='60%'
        if (this.stepsActive < 0) {
          this.stepsActive = 2;
          this.drawWidth='40%'
        }
      },
      /* 下一步 */
      stepsNext() {
        console.log("this.rules222",this.rules,'this.fileList ',this.fileList,'this.bgImgs',this.bgImgs )
        if(this.bgImgs.length>0){
          this.form.backgroundImage=1
        }
        this.$refs.form.validate((valid, obj) => {
          console.log('valid',valid,'obj',obj)
          for(let i in obj){
            console.log("i",i)
            console.log("obj=========",obj[i][0].message)
            this.hint=obj[i][0].message
            break
          }
          console.log('this.hint',this.hint,'22form',this.form)
          if (valid) {
            // titleType 1:语音文件 2：添加字幕
            /*if(this.bgImgs.length<=0){
              this.$message.error("请上传背景图")
              return
            }*/
            if(this.form.titleType==1 && this.explanList.length <=0){
              this.$message.error("请上传解说语音文件")
              return
            }
            // this.loading=true
            console.log("this.explanList============",this.explanList)
            this.point=0
            let durationAll=0
            // form.titleType=1 语音文件 2：添加字幕：需调用接口转换时长计算点数
            if(this.form.titleType==1){
              for(let i=0;i<this.explanList.length;i++){
                durationAll+=Number(this.explanList[i].duration)
              }
              console.log("总durationAll==", durationAll)
              this.point=(durationAll*0.165).toFixed(2)
              console.log("总point==", this.point)
              this.stepsActive++;
              this.drawWidth='40%'
              if (this.stepsActive > 2) {
                this.stepsActive = 0;
                this.drawWidth='60%'
              }
            }
            else{
              /*let file='https://yunhunjian123.oss-cn-shanghai.aliyuncs.com/55555.MP3'
              ossUpdate2(file,localStorage.getItem('username'))
                       .then((data) => {
                         let url=data.msg
                         console.log("ossUpdate2==data",data)
                         registerAssetsMedia({
                           mediaUrl:url,//上传阿里云生成的地址
                           mediaType:'audio/mpeg',//文件类型,已固定，如果需动态，可设置
                           username:this.$store.state.user.info.username
                         })
                           .then((mediaData) => {
                             console.log('mediaData.data.duration',mediaData)
                           })
                           .catch((e) => {
                             this.loading=false
                             this.$message.error(e);
                           });
                       })
                       .catch((e) => {
                         this.loading=false
                         this.$message.error(e);
                       });*/
              let circulateLength=0
              let file=''
              this.form.texts = this.form.textList.map(function(e,i){
                return e.content
              }).join(',')
              getSubmitAudioProduceJob(this.form.texts)
                .then((data) => {
                  let explanList=data.data
                  console.log("data222",data)

                  this.loading=true
                  let duration=''
                  setTimeout(()=>{
                    for(let i=0;i<explanList.length;i++){
                      // durationAll+=Number(this.explanList[i].duration)
                      // 嵌套，需修改
                      // 获取音频时长
                      // let file = "https://yunhunjian123.oss-cn-shanghai.aliyuncs.com/55555.MP3"
                      // 字幕非接口调用查看时长，查询网址：https://blog.csdn.net/weixin_61285710/article/details/122468789，但URL.createObjectURL，会报错
                      file=explanList[i]
                      /* registerAssetsMedia({
                         mediaUrl:file,//上传阿里云生成的地址
                         mediaType:'audio/mpeg',//文件类型,已固定，如果需动态，可设置
                         username:this.$store.state.user.info.username
                       })
                         .then((mediaData) => {
                           console.log('mediaData.data.duration',mediaData.data.duration,'mediaData',mediaData)
                           duration=mediaData.data.duration
                         })
                         .catch((e) => {
                           this.loading=false
                           this.$message.error(e);
                         });*/
                      ossUpdate2(file,localStorage.getItem('username'))
                        .then((data) => {
                          let url=data.msg
                          console.log("ossUpdate2==data",data)
                          registerAssetsMedia({
                            mediaUrl:url,//上传阿里云生成的地址
                            mediaType:'audio/mpeg',//文件类型,已固定，如果需动态，可设置
                            username:this.$store.state.user.info.username
                          })
                            .then((mediaData) => {
                              console.log('mediaData.data.duration',mediaData.data.duration,'mediaData',mediaData)
                              duration=mediaData.data.duration
                              console.log("duration",duration)
                              durationAll+=Number(duration)
                              circulateLength+=1
                              console.log("circulateLength2222",circulateLength,'explanList.length',explanList.length)
                              // 判断循环的次数等于字幕的长度，则跳转下一步
                              if(circulateLength>=explanList.length){
                                this.loading=false
                                console.log("总durationAll==", durationAll)
                                this.point=(durationAll*0.165).toFixed(2)
                                console.log("总point==", this.point)
                                this.stepsActive++;
                                this.drawWidth='40%'
                                if (this.stepsActive > 2) {
                                  this.stepsActive = 0;
                                  this.drawWidth='60%'
                                }
                              }
                            })
                            .catch((e) => {
                              this.loading=false
                              // this.$message.error(e);
                            });
                        })
                        .catch((e) => {
                          this.loading=false
                          // this.$message.error(e);
                        });
                    }
                  },5000)
                  /*setTimeout(()=>{
                    this.loading=false
                    console.log("总durationAll==", durationAll)
                    this.point=(durationAll*0.165).toFixed(2)
                    console.log("总point==", this.point)
                    this.stepsActive++;
                    this.drawWidth='40%'
                    if (this.stepsActive > 2) {
                      this.stepsActive = 0;
                      this.drawWidth='60%'
                    }
                  },10000)*/
                })
                .catch((e) => {
                  this.$message.error(e);
                });

            }


          } else {
            console.log("进入非空提示",valid,'22',this.form)
            this.$message.error(this.hint)
            return false;
          }
        });
      },
      // types:1女 2男
      // types 存在代表是，形象展示发布进入，否则是新建任务进入
      getAiList(e,types){
        if(types==2){
          this.isHaveAi=true
        }
        console.log("一进入组件调用e,types",e,types)
        this.aiList=e
        if(types){
          this.screenSex(types)
        }
      },
      // 根据传入的数组人性别，去筛选aiList
      screenSex(sex){
        // sex 1：女 2:男
        if(sex==1){
          this.aiList=this.aiList.filter(i => {
            i.szr_name=i.describe+'-'+i.szr_name
            return i.status == 1;
          });
        }
        else {
          this.aiList=this.aiList.filter(i=>{
            i.szr_name=i.describe+'-'+i.szr_name
            return i.status==2
          })
        }
        console.log('筛选后的this.aiList=',this.aiList)
      },
      /* 数字人形象赋值 */
      show(e,type) {
        console.log("show===========e",e)
        this.detailInfo=e
        this.form.imageId=e.id
        //type=1,代表是，表格新建形象，需要字段标识
        if(type==1){
          this.isNewImage=true
          this.screenSex(e.types)
        }
      },
      // “打开形象” 弹框
      openImage(){
        console.log("打开形象弹框======",this.$refs['image'])
        this.$nextTick(()=>{
          this.$refs['image'].show()
        })
      },
      // 解说设置
      explainSet(e){
        console.log('e',e)
      },

      clearExplan(index){
        this.explanList.splice(index,1)
        this.form.voiceFiles.splice(index,1)
        /*this.explanList=[]
        this.form.voiceFiles=[]  //全程解说参数名(校检赋值)*/
        this.$message.success('删除成功！')
      },

      // 文本start
      changeMney(data,index){
        console.log("进入修改=========")
        this.$set(this.form.textList[index],'content',data.content)
        if(data.content.length>=5){
          this.$set(this.form.textList[index],'isText',true)
        }
        else{
          this.$set(this.form.textList[index],'isText','')
        }
        let arr=[];  //新数组
        this.form.textList.forEach(item=>{
          arr.push(item);
        })
        this.form.textList=arr;//相当于返回一个新数组可以触发渲染
        console.log('this.form.textList',this.form.textList)

      },
      //  加
      add(){
        let content={content:''}
        this.form.textList.push(content)
        console.log('this.form.textList',this.form.textList,this.form.textList.length)
      },
      //减
      subtract(index){
        this.form.textList.splice(index, 1)
        console.log("this.form.textList",this.form.textList,this.form.textList.length)
      },
      // end

      /* 删除增加确认弹窗 */
      onBeforeRemove() {
        return new Promise((resolve, reject) => {
          this.$confirm('确定要删除吗?', '提示', {
            type: 'warning'
          })
            .then(() => {
              resolve();
            })
            .catch(() => {
              reject();
            });
        });
      },
      /* 更新 visible */
      updateVisible(value) {
        if(value==false){
          console.log("进入false======",this.form,'this.defaultForm',this.defaultForm)
          this.saveClear()
          /*清除形象数据*/
          if(this.isNewImage){
            delete this.form.imageId
            this.detailInfo.image= ''
          }
        }
        this.$emit('update:visible', value);
      },

      // 重置
      resetting(){
        this.saveClear()
      },
      /*清空创建形象*/
      saveClear(){
        this.form={ ...this.defaultForm }
        this.form.voiceFiles=[]
        this.form.textList=[{
          content:'',
          isText:''
        }],
          this.explanList=[]
        this.bgImgs=[]
        this.fileList=[]
        this.stepsActive=0
      },
      // 备份
      confirm22(){
        console.log("this.rules222",this.rules,'this.fileList ',this.fileList,'this.bgImgs',this.bgImgs )
        if(this.bgImgs.length>0){
          this.form.backgroundImage=1
        }
        this.$refs.form.validate((valid, obj) => {
          console.log('valid',valid,'obj',obj)
          for(let i in obj){
            console.log("i",i)
            console.log("obj=========",obj[i][0].message)
            this.hint=obj[i][0].message
            break
          }
          console.log('this.hint',this.hint,'22form',this.form)
          if (valid) {
            // titleType 1:语音文件 2：添加字幕
            /*if(this.bgImgs.length<=0){
              this.$message.error("请上传背景图")
              return
            }*/
            if(this.form.titleType==1 && this.explanList.length <=0){
              this.$message.error("请上传解说语音文件")
              return
            }
            this.loading=true
            this.uploadBj()  // 上传背景图
          } else {
            console.log("进入非空提示",valid,'22',this.form)
            this.$message.error(this.hint)
            return false;
          }
        });
      },
      confirm(){
        this.loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: '#ffffffe6'
        });
        // this.loading = true;
        this.uploadBj()  // 上传背景图
      },
      async uploadBj(){
        if(this.bgImgs.length < 1) {
          this.$message.error('请选择文件后提交');
        }
        // 获取文件上传签名数据
        this.data = await userOssSignature()
        for(let i=0;i<this.bgImgs.length;i++){
          let file = this.bgImgs[i].file
          let filename=file.name;
          let markIndex=(filename).lastIndexOf('.');
          let suffix=filename.substring(markIndex)    // 图片后缀(例.jpg)
          let date=new Date().getTime();    // 当前时间戳
          // 构建请求参数
          let param = new FormData()
          param.append("key", this.data.dir + date+suffix)
          param.append("policy", this.data.policy)
          param.append("OSSAccessKeyId", this.data.accessId)
          param.append("success_action_status", '200')
          // param.append("callback",  this.data.callback)     //回调（not)
          param.append("signature", this.data.signature)
          param.append("file", file, file.name)
          param.append('success_action_status', '200')
          let config = {
            headers: {
              'Access-Control-Allow-Origin': '*',
              'x-oss-callback-Authorization': getToken()
            }
          }
          axios.post(this.data.host, param, config).then(res => {
            if(res.status==200){
              console.log('this.data.host',this.data.host+'/'+date+suffix)
              let url=this.data.host+'/'+date+suffix;
              this.form.backgroundImage=url;
              // titleType 1:语音文件 2：添加字幕
              if(this.form.titleType==1){
                this.form.voiceFiles=this.form.voiceFiles.join(',');   // 数组转字符串
                console.log("转换后的 this.form.voiceFiles", this.form.voiceFiles,"this.explanList============",this.explanList)
                delete this.form.textList
                delete this.form.texts

                delete this.form.volume
                delete this.form.speechSpeed
                delete this.form.intonation
                delete this.form.showSubtitles
                delete this.form.voice
              }
              if(this.form.titleType==2){
                this.form.texts = this.form.textList.map(function(e,i){
                  return e.content
                }).join(',')
                this.explanList=[]
                delete this.form.textList
                this.form.textList=[{
                  content:'',
                  isText:''
                }],
                  delete this.form.voiceFiles
              }

              console.log(" this.form", this.form)
              this.form.counts=this.point
              this.save()
            }
            else{
              this.loading=false
              this.$message.error('上传失败');
            }

          }).catch(err => {
            console.log(err)
          })
        }
      },
      save(){
        console.log("ssave========",this.form,"this.explanList============",this.explanList)
        createTask(this.form)
          .then((data) => {
            this.loading.close();
            // this.loading = false;
            this.$message.success("提交成功！")
            console.log("提交成功data",data)
            this.updateVisible(false)
            this.$emit('load')
          })
          .catch((e) => {
            // 由于字幕保存时转为了字符串，使用失败后，直接清除，否则会出现多条数据
            this.form.voiceFiles=[]
            /* this.form.texts=[{
               content:''
             }],*/
            this.loading.close();
            // this.loading = false;
            this.$message.error(e);
          });
      },

      beforeAvatarUpload(file) {
        let isSize = true;
        const reader = new FileReader();
        console.log("reader",reader)
        reader.readAsDataURL(file);
        reader.onload = (theFile) => {
          const image = new Image();
          console.log("theFile",theFile)
          image.src = theFile.target.result;
          image.onload = () => {
            const { width, height } = image;
            // {{detailInfo.resolutionType==4 ? '1920px * 1080px' :'1080px * 1920px'}}
            let kuan,gao=0
            if(this.detailInfo.resolutionType==4){
              kuan=1920
              gao=1080
            }
            else{
              kuan=1080
              gao=1920
            }

            if(width !== kuan || height !== gao) {
              this.$message.error('请上传'+kuan+'px' +'*'+gao+'px 的图片！');
              isSize = false;
              this.bgImgs=[]  //背景图清空，由于isSize=false 未及时在return时返回，so，需要在分辨率错误后，清空背景图数据
              console.log('isSize',isSize);
            };
          };
        };

        // const isJPG = file.type === 'image/jpeg';
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 2;

        const extension1 = file.type === "image/jpg";
        const extension2 = file.type === "image/jpeg";
        const extension3 = file.type === "image/png";
        if (!extension1 && !extension2 && !extension3) {
          this.$message.error("请上传jpg 、png、jpeg 类型图片!");
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }

        console.log('isJPG && isLt2M && isSize',isJPG && isLt2M && isSize,isJPG,isLt2M,isSize)

        return isJPG && isLt2M && isSize;
      },
      // 上传 start
      uploadClick(file){
        /*if(this.explanList.mediaId){
          this.$message.error('最多上传一条全程解说！可删除重试')
          return
        }*/
        console.log("进入点击事件",this.explanList,this.explanList.mediaId)
        this.fileList.push(file)
        this.selectVideo();
      },
      async selectVideo(){
        console.log(" this.fileList", this.fileList)
        if(this.fileList.length < 1) {
          console.log("请选择文件后提交")
          return
        }
        console.log('组件调用2222================================')
        this.data = await userOssSignature()
        let file = this.fileList[0].raw
        console.log(file)
        this.filename=file.name;
        let markIndex=( this.filename).lastIndexOf('.');
        let suffix= this.filename.substring(markIndex)
        let name = this.filename.substring(0, markIndex); // 截取除 .png前的字段名
        let date=new Date().getTime();
        // 构建请求参数
        let param = new FormData()
        param.append("key", this.data.dir + name + '.' + date + suffix)
        param.append("policy", this.data.policy)
        param.append("OSSAccessKeyId", this.data.accessId)
        param.append("success_action_status", '200')
        // param.append("callback",  this.data.callback)     //回调（not)
        param.append("signature", this.data.signature)
        param.append("file", file, file.name)
        param.append('success_action_status', '200')
        let config = {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'x-oss-callback-Authorization': getToken()
          }
        }
        console.log("suffix",suffix)
        axios.post(this.data.host, param, config).then(res => {
          if(res.status==200){
            console.log('this.data.host', this.data.host + '/' + name + '.'  + date + suffix)
            let url = this.data.host + '/' + name + '.' + date + suffix;
            let type=file.type;
            console.log('file.type',file.type)
            this.fileList=[]
            this.registerMedias(url,type);
          }
          else{
            this.$message.error('上传失败');
          }

        }).catch(err => {
          console.log(err)
        })
      },
      registerMedias(url,type) {
        registerAssetsMedia({
          mediaUrl:url,//上传阿里云生成的地址
          mediaType:type,//文件类型
          username:this.$store.state.user.info.username
        })
          .then((data) => {
            this.$message.success("上传成功！")
            console.log("data",data)
            // this.musicList.push(data.data)

            /*名称截取start*/
            let filename=data.data.fileName
            let markIndex = (filename).lastIndexOf('.');
            let suffix = filename.substring(markIndex)  // 图片后缀
            filename=filename.split('.')[0]+suffix
            /*名称截取end*/

            let list={
              url:data.data.mediaUrl,
              fileName:filename,
              duration:data.data.duration,
              mediaId:data.data.mediaId
            }
            console.log('list',list)
            this.explanList.push(list)
            console.log("this.explanList============",this.explanList)
            this.form.voiceFiles.push( list.url)   //全程解说参数名
            console.log("this.form.voiceFiles",this.form.voiceFiles)
          })
          .catch((e) => {
            this.$message.error(e);
          });
      },
      //  上传音频end
    }
  }
</script>

<style scoped lang="less">
  .img-btn{
    height: 164px;
    width: 100px;
    font-size: 30px;
    background: #fafafa;
    color: #c0c4cc;
    border: 1px dashed #c0c4cc;
  }
  .img-btn:hover{
    border: 1px dashed #1890ff
  }
  .d-musiz-class{
    border:1px solid #ddd;
    border-radius: 6px;
    padding: 5px 10px 0;
    .m-bottom5{
      margin-bottom: 5px;
    }
    img{
      width: 23px;
      margin-right: 10px;
    }
    button{
      border: none;
      padding: 5px 10px;
      font-size: 16px;
    }
  }

  .btn-position{
    margin-left: 20px;
  }
  /*点数样式*/
  .d-point-cls{
    padding:30px;
    font-size: 20px;
    color: #333;
    span{
      margin-left: 10px;
      font-size: 28px;
      color: red;
      font-weight: bold;
    }
  }
</style>
